<template>
  <div class="forgot-password-page">
    <div class="forgot-password-container">
      <!-- Header -->
      <div class="header">
        <van-nav-bar title="Reset Password" left-text="Back" left-arrow @click-left="$router.back()" />
      </div>

      <div class="content">
        <!-- Step 1: Enter Email -->
        <div v-if="currentStep === 1" class="step-content">
          <div class="step-header">
            <van-icon name="lock" class="step-icon" />
            <h2 class="step-title">Forgot your password?</h2>
            <p class="step-description">
              Enter your email address and we'll send you a link to reset your password.
            </p>
          </div>

          <van-form @submit="handleSendResetEmail" class="reset-form">
            <div class="form-fields">
              <div class="field-group">
                <label class="field-label">Email</label>
                <van-field v-model="resetForm.email" name="email" placeholder="Enter your email" :rules="[
                  { required: true, message: 'Email is required' },
                  { validator: validateEmail, message: 'Please enter a valid email' }
                ]" clearable class="custom-field" />
              </div>
            </div>

            <div class="form-actions">
              <van-button round block type="primary" native-type="submit" :loading="loading" class="reset-btn">
                Send Reset Link
              </van-button>
            </div>
          </van-form>
        </div>

        <!-- Step 2: Email Sent Confirmation -->
        <div v-else-if="currentStep === 2" class="step-content">
          <div class="step-header">
            <van-icon name="success" class="step-icon success" />
            <h2 class="step-title">Check your email</h2>
            <p class="step-description">
              We've sent a password reset link to <strong>{{ resetForm.email }}</strong>
            </p>
          </div>

          <div class="email-instructions">
            <p>Didn't receive the email? Check your spam folder or</p>
            <van-button type="primary" plain size="small" :loading="resendLoading" @click="handleResendEmail"
              class="resend-btn">
              Resend email
            </van-button>
          </div>

          <div class="form-actions">
            <van-button round block @click="$router.push('/auth/login')" class="back-login-btn">
              Back to Login
            </van-button>
          </div>
        </div>

        <!-- Step 3: Reset Password Form -->
        <div v-else-if="currentStep === 3" class="step-content">
          <div class="step-header">
            <van-icon name="lock" class="step-icon" />
            <h2 class="step-title">Create new password</h2>
            <p class="step-description">
              Your new password must be different from previous used passwords.
            </p>
          </div>

          <van-form @submit="handleResetPassword" class="reset-form">
            <div class="form-fields">
              <div class="field-group">
                <label class="field-label">New Password</label>
                <van-field v-model="resetForm.password" type="password" name="password" placeholder="Enter new password"
                  :rules="[
                    { required: true, message: 'Password is required' },
                    { validator: validatePasswordStrength, message: 'Password is too weak' }
                  ]" clearable class="custom-field" @input="checkPasswordStrength" />

                <!-- Password Strength Indicator -->
                <div v-if="resetForm.password" class="password-strength">
                  <div class="strength-bar">
                    <div class="strength-fill" :class="passwordStrength.strength"
                      :style="{ width: getStrengthWidth() }">
                    </div>
                  </div>
                  <div class="strength-text">
                    Password strength: {{ passwordStrength.strength }}
                  </div>
                </div>
              </div>

              <div class="field-group">
                <label class="field-label">Confirm Password</label>
                <van-field v-model="resetForm.password_confirmation" type="password" name="password_confirmation"
                  placeholder="Confirm new password" :rules="[
                    { required: true, message: 'Password confirmation is required' },
                    { validator: validatePasswordMatch, message: 'Passwords do not match' }
                  ]" clearable class="custom-field" />
              </div>
            </div>

            <div class="form-actions">
              <van-button round block type="primary" native-type="submit" :loading="loading" class="reset-btn">
                Reset Password
              </van-button>
            </div>
          </van-form>
        </div>

        <!-- Step 4: Success -->
        <div v-else-if="currentStep === 4" class="step-content">
          <div class="step-header">
            <van-icon name="success" class="step-icon success" />
            <h2 class="step-title">Password reset successful</h2>
            <p class="step-description">
              Your password has been successfully reset. You can now sign in with your new password.
            </p>
          </div>

          <div class="form-actions">
            <van-button round block type="primary" @click="$router.push('/auth/login')" class="login-btn">
              Sign In
            </van-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { validateEmail, validatePassword, validatePasswordConfirmation } from '@/utils/validate'
import { authApi } from '@/api/auth'
import type { ResetPasswordData } from '@/types/user'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const resendLoading = ref(false)
const currentStep = ref(1)

const resetForm = reactive<ResetPasswordData & { email: string }>({
  email: '',
  token: '',
  password: '',
  password_confirmation: ''
})

const passwordStrength = ref({
  isValid: false,
  strength: 'weak' as 'weak' | 'medium' | 'strong',
  issues: [] as string[]
})

onMounted(() => {
  // Check if we have a reset token in the URL
  const token = route.query.token as string
  const email = route.query.email as string

  if (token && email) {
    resetForm.token = token
    resetForm.email = email
    currentStep.value = 3
  }
})

const checkPasswordStrength = () => {
  if (resetForm.password) {
    passwordStrength.value = validatePassword(resetForm.password)
  }
}

const getStrengthWidth = () => {
  switch (passwordStrength.value.strength) {
    case 'weak': return '33%'
    case 'medium': return '66%'
    case 'strong': return '100%'
    default: return '0%'
  }
}

const validatePasswordStrength = (value: string) => {
  const result = validatePassword(value)
  return result.isValid
}

const validatePasswordMatch = (value: string) => {
  return validatePasswordConfirmation(resetForm.password, value)
}

const handleSendResetEmail = async () => {
  try {
    loading.value = true
    await authApi.forgotPassword(resetForm.email)

    showToast({
      type: 'success',
      message: 'Reset link sent to your email'
    })

    currentStep.value = 2

  } catch (error: any) {
    showToast({
      type: 'fail',
      message: error.message || 'Failed to send reset email'
    })
  } finally {
    loading.value = false
  }
}

const handleResendEmail = async () => {
  try {
    resendLoading.value = true
    await authApi.forgotPassword(resetForm.email)

    showToast({
      type: 'success',
      message: 'Reset link sent again'
    })

  } catch (error: any) {
    showToast({
      type: 'fail',
      message: error.message || 'Failed to resend email'
    })
  } finally {
    resendLoading.value = false
  }
}

const handleResetPassword = async () => {
  try {
    loading.value = true
    await authApi.resetPassword({
      token: resetForm.token,
      email: resetForm.email,
      password: resetForm.password,
      password_confirmation: resetForm.password_confirmation
    })

    showToast({
      type: 'success',
      message: 'Password reset successfully'
    })

    currentStep.value = 4

  } catch (error: any) {
    showToast({
      type: 'fail',
      message: error.message || 'Failed to reset password'
    })
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.forgot-password-page {
  min-height: 100vh;
  background: $background-color;
}

.forgot-password-container {
  max-width: 400px;
  margin: 0 auto;
  background: $white;
  min-height: 100vh;
}

.header {
  position: sticky;
  top: 0;
  z-index: 100;
  background: $white;
  border-bottom: 1px solid $border-color;
}

.content {
  padding: $spacing-lg;
}

.step-content {
  .step-header {
    text-align: center;
    margin-bottom: $spacing-xl;

    .step-icon {
      font-size: 48px;
      color: $primary-color;
      margin-bottom: $spacing-md;

      &.success {
        color: $success-color;
      }
    }

    .step-title {
      font-size: $font-size-xl;
      font-weight: $font-weight-bold;
      color: $text-color;
      margin-bottom: $spacing-sm;
    }

    .step-description {
      font-size: $font-size-md;
      color: $text-color-3;
      line-height: 1.5;
    }
  }
}

.reset-form {
  margin-bottom: $spacing-lg;
}

.form-fields {
  margin-bottom: $spacing-lg;

  .field-group {
    margin-bottom: $spacing-xl;

    .field-label {
      display: block;
      font-size: $font-size-lg;
      font-weight: $font-weight-bold;
      color: $text-color;
      margin-bottom: 8px;
    }

    .custom-field {
      :deep(.van-cell) {
        height: 46px;
        padding: 0 $spacing-md;
        background: $white;
        border: 2px solid $border-color;
        border-radius: $border-radius-md;
        box-shadow: none;
        display: flex;
        align-items: center;

        &:focus-within {
          border-color: $danger-color;
        }
      }

      :deep(.van-field__control) {
        height: 100%;
        font-size: $font-size-md;
        color: $text-color;
        line-height: 1;

        &::placeholder {
          color: $text-color-3;
        }
      }

      :deep(.van-field__label) {
        display: none;
      }

      :deep(.van-field__left-icon) {
        display: none;
      }

      :deep(.van-field__clear) {
        color: $text-color-3;
      }
    }
  }
}

.password-strength {
  margin-top: $spacing-sm;

  .strength-bar {
    height: 4px;
    background: $gray-3;
    border-radius: 2px;
    overflow: hidden;
    margin-bottom: $spacing-xs;

    .strength-fill {
      height: 100%;
      transition: width 0.3s ease;

      &.weak {
        background: $danger-color;
      }

      &.medium {
        background: $warning-color;
      }

      &.strong {
        background: $success-color;
      }
    }
  }

  .strength-text {
    font-size: $font-size-xs;
    color: $text-color-3;
    text-transform: capitalize;
  }
}

.email-instructions {
  text-align: center;
  margin: $spacing-xl 0;

  p {
    font-size: $font-size-sm;
    color: $text-color-3;
    margin-bottom: $spacing-sm;
  }

  .resend-btn {
    font-size: $font-size-sm;
  }
}

.form-actions {
  margin: $spacing-xl 0;

  .reset-btn,
  .back-login-btn,
  .login-btn {
    height: 48px;
    font-size: $font-size-lg;
    font-weight: $font-weight-medium;
  }

  .back-login-btn {
    background: $gray-1;
    color: $text-color;
    border: none;
  }
}
</style>